<template>
  <el-form
    label-width="80"
    :model="skuParams"
    :rules="rules"
    scrollToField
    ref="skuValida"
  >
    <el-form-item label="SKU名称" prop="skuName">
      <el-input
        type="text"
        placeholder="sku名称"
        v-model.trim="skuParams.skuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
      <el-input
        type="number"
        placeholder="价格(元)"
        v-model.trim="skuParams.price"
      ></el-input>
    </el-form-item>
    <el-form-item label="重量(克)" prop="weight">
      <el-input
        type="number"
        placeholder="重量(克)"
        v-model.trim="skuParams.weight"
      ></el-input>
    </el-form-item>
    <el-form-item label="SKU描述" prop="skuDesc">
      <el-input
        type="textarea"
        placeholder="sku描述"
        v-model.trim="skuParams.skuDesc"
      ></el-input>
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form class="double-item" :inline="true">
        <el-form-item
          :label="attr1.attrName"
          v-for="attr1 in attr"
          :key="attr1.id"
        >
          <el-select placeholder="请选择" v-model="attr1.AttrIdAndValueId">
            <el-option
              :label="val.valueName"
              v-for="val in attr1.attrValueList"
              :key="val.id"
              :value="`${attr1.id}:${val.id}`"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form class="double-item">
        <el-form-item
          v-for="sal in saleAttr"
          :key="sal.id"
          :label="sal.saleAttrName"
        >
          <el-select style="width: 240px" v-model="sal.saleIdAndValueId">
            <el-option
              v-for="salVal in sal.spuSaleAttrValueList"
              :key="salVal.id"
              :label="salVal.saleAttrValueName"
              :value="`${sal.id}:${salVal.id}`"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="图片名称">
      <el-table
        ref="table"
        border
        :header-cell-style="{ 'text-align': 'center' }"
        :data="imgAttr"
      >
        <el-table-column type="selection" width="80" align="center" />
        <el-table-column label="图片">
          <template #default="{ row }">
            <el-image :src="row.imgUrl" fit="fill" :lazy="true"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <el-button
              :plain="defSel == $index ? true : false"
              :type="defSel == $index ? 'warning' : ''"
              :size="defSel == $index ? 'larger' : 'small'"
              @click="defaultImg(row, $index)"
            >
              {{ defSel == $index ? '默认展示图片' : '设为默认展示图片' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="onSaveSku">
        保存
      </el-button>
      <el-button size="default" @click="cancle">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup name="skuForm">
import { getAttrList } from '@/api/product/attr'
import {
  AddSku,
  ImageWall,
  SpuList,
  spuSaleAttrData,
} from '@/api/product/spu/type'
import { addSku, getSaleSpuAttr, getSpuImageWall } from '@/api/product/spu'
import { Attr } from '@/api/product/attr/type'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { reqSkuInfo, upDateGetInfo } from '@/api/product/sku'
import { SkuRecords } from '@/api/product/sku/type'
//接收请求的属性，以及临时携带下拉框选择的数据
let attr = ref<Attr[]>([])
//接收请求的照片，用于选择sku默认图片
let imgAttr = ref<ImageWall[]>([])
//接收请求的销售属性，以及临时携带下拉框选择的数据
let saleAttr = ref<spuSaleAttrData[]>([])
//收集表单数据
let skuParams = reactive<AddSku>({
  category3Id: '',
  spuId: '',
  tmId: '',
  skuName: '',
  price: '',
  weight: '',
  skuDefaultImg: '',
  skuDesc: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
})
//tableSelection复选框的单选选中
const table = ref()
//控制按钮的选中状态
let defSel = ref(0)
//ref用于验证所有表单项
let skuValida = ref()
//接收自定义事件
const $emits = defineEmits(['sen'])
//取消添加
const cancle = () => {
  // 清空表单数据
  initialization()
  $emits('sen', { flag: 0, params: '' })
}
//初始化一个清空数据的方法
const initialization = () => {
  attr.value = []
  imgAttr.value = []
  saleAttr.value = []
  const inis = {
    category3Id: '',
    spuId: '',
    tmId: '',
    skuName: '',
    price: '',
    weight: '',
    skuDefaultImg: '',
    skuDesc: '',
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
  }
  //深拷贝清空数据
  Object.assign(skuParams, JSON.parse(JSON.stringify(inis)))
}
//初始化数据的地方
const initStart = async (c1Id: number, c2Id: number, row: SpuList) => {
  //在添加和请求数据前先清空表单数据
  initialization()
  //在进行赋值操作
  skuParams.category3Id = row.category3Id
  skuParams.spuId = row.id as number
  skuParams.tmId = row.tmId
  //属性
  const result = await getAttrList(c1Id, c2Id, row.category3Id)
  //spu销售属性
  const result2 = await getSaleSpuAttr(row.id as number)
  //spu图片
  const result3 = await getSpuImageWall(row.id as number)
  attr.value = result.data
  imgAttr.value = result3.data
  saleAttr.value = result2.data
  //后端没有开这个接口本来是需要上传这个的
  // skuParams.skuImageList = result3.data
}
//修改初始化数据的地方
const initUpdate = async (row: SkuRecords) => {
  ElMessage({
    type: 'warning',
    message: '此功能目前还没有投入使用正在努力开发中......',
    duration: 600000,
    offset: 100,
    showClose: true,
  })
  if (row.spuId != null) {
    //在添加和请求数据前先清空表单数据
    // initialization()
    const result = await reqSkuInfo(row.spuId)
    //spu销售属性
    const result2 = await getSaleSpuAttr(row.spuId as number)
    //spu图片
    const result3 = await getSpuImageWall(row.spuId as number)
    Object.assign(skuParams, JSON.parse(JSON.stringify(result.data)))
    imgAttr.value = result3.data
    saleAttr.value = result2.data
    let data = result.data
    data.skuAttrValueList.forEach((item) => {
      let bbq = []
      bbq.push({
        valueName: item.valueName,
        id: item.valueId,
      })
      attr.value.push({
        AttrIdAndValueId: item.attrId + ':' + item.valueId,
        id: item.attrId as number,
        attrName: item.attrName as string,
        categoryId: '',
        categoryLevel: 0,
        attrValueList: bbq as [],
      })
    })

    saleAttr.value.forEach((item) => {
      item.spuSaleAttrValueList.forEach((item2) => {
        item.saleIdAndValueId = item.id + ':' + item2.id
      })
    })
    let index = ref(0)
    imgAttr.value.forEach((item, ind) => {
      if (item.imgUrl == row.skuDefaultImg) {
        index.value = ind
      }
    })
    defSel.value = index.value
  } else {
    ElMessage({ type: 'warning', message: '系统数据！！！' })
  }
}
//设置默认图片
const defaultImg = (row: any, index: number) => {
  //设为默认图片后赋值给skuParams
  skuParams.skuDefaultImg = row.imgUrl
  table.value.clearSelection()
  table.value.toggleRowSelection(row, true)
  defSel.value = index
}
//保存按钮
const onSaveSku = async () => {
  //整理参数
  //把靠在Attr属性上的数据取出来
  skuParams.skuAttrValueList = attr.value.reduce((pre: any, next: any) => {
    if (next.AttrIdAndValueId) {
      pre.push({
        attrId: Number(next.AttrIdAndValueId?.split(':')[0]),
        valueId: Number(next.AttrIdAndValueId?.split(':')[1]),
      })
    }
    return pre
  }, [])
  //把靠在saleAttr销售属性上的数据取出来
  skuParams.skuSaleAttrValueList = saleAttr.value.reduce(
    (pre: any, next: any) => {
      if (next.saleIdAndValueId) {
        pre.push({
          saleAttrId: Number(next.saleIdAndValueId?.split(':')[0]),
          saleAttrValueId: Number(next.saleIdAndValueId?.split(':')[1]),
        })
      }
      return pre
    },
    [],
  )
  //验证表单
  await skuValida.value.validate().catch(() => {
    ElMessage({ type: 'error', message: '请填写完整数据' })
  })
  if (skuParams.id) {
    await upDateGetInfo(skuParams)
      .then((result) => {
        if (result.code == 200) {
          ElMessage({ type: 'success', message: '添加成功' })
          $emits('sen', { flag: 0, params: '' })
        } else {
          ElMessage({ type: 'warning', message: '' + result.code })
        }
      })
      .catch((error: any) => {
        ElMessage({ type: 'error', message: error })
      })
  } else {
    // 向服务器携带数据添加sku
    await addSku(skuParams)
      .then((result) => {
        if (result.code == 200) {
          ElMessage({ type: 'success', message: '添加成功' })
          $emits('sen', { flag: 0, params: '' })
        } else {
          ElMessage({ type: 'warning', message: '' + result.code })
        }
      })
      .catch((error: any) => {
        ElMessage({ type: 'error', message: error })
      })
  }
}
//价格验证规则
const priceValidator = (rule: any, value: any, callback: any) => {
  if (value == '') {
    callback(new Error('价格不能为空'))
  } else {
    if (value < 1000) {
      callback(new Error('定价过低注意'))
    }
  }
  callback()
}
//重量验证规则
const weightValidator = (rule: any, value: any, callback: any) => {
  if (value <= 0) {
    callback(new Error('重量不能小于等于0'))
  } else if (value == '') {
    callback(new Error('重量为必填项'))
  }
  callback()
}
const rules = reactive({
  skuName: [{ required: true, message: 'sku名称为必填项', trigger: 'blur' }],
  price: [
    {
      required: true,
      trigger: 'blur',
      validator: priceValidator,
    },
  ],
  weight: [{ required: true, validator: weightValidator, trigger: 'blur' }],
  skuDesc: [
    {
      required: true,
      min: 10,
      max: 1000,
      message: '描述为必填项且不能小于10个字符',
      trigger: 'change',
    },
  ],
})
defineExpose({ initStart, initUpdate })
</script>
<style scoped lang="scss">
.double-item {
  width: 100%;
  .el-form-item {
    width: 25%;
    margin: 5px 20px;
  }
}
</style>
